package com.github.elliot.gatewaycenter.security.handlers;

import com.github.elliot.gatewaycenter.common.ServerResponseEntity;
import com.github.elliot.gatewaycenter.domain.AdminUserPO;
import com.github.elliot.gatewaycenter.security.jwt.JwtTokenGenerator;
import com.github.elliot.gatewaycenter.security.jwt.JwtTokenPair;
import com.github.elliot.gatewaycenter.util.WebExchangeUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 自定义认证成功处理器
 */
@Slf4j
@Component
public class CustomServerAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler {

    @Autowired
    private JwtTokenGenerator jwtTokenGenerator;

    @Override
    @SneakyThrows
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        AdminUserPO adminUserPo = (AdminUserPO) authentication.getPrincipal();

        log.info("CustomServerAuthenticationSuccessHandler user:{} authentication success", adminUserPo.getUsername());

        Map<String, String> additional = new HashMap<>();
        additional.put("username", adminUserPo.getUsername());
        additional.put("userNo", adminUserPo.getUserNo());
        additional.put("mobile", adminUserPo.getMobile());
        additional.put("mail", adminUserPo.getMail());

        Set<String> roleSet = new HashSet<>();

        JwtTokenPair token = jwtTokenGenerator.jwtTokenPair(adminUserPo.getUserNo(), roleSet, additional);

        return WebExchangeUtils.writeJsonResponse(webFilterExchange.getExchange(),
                HttpStatus.OK, ServerResponseEntity.success(token));

    }
}
